package com.tckj.boot.modules.domain.obj.news;

import com.tckj.boot.modules.domain.obj.news.dto.NewsDTO;
import com.tckj.boot.modules.domain.obj.news.dto.NewsQueryCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.tckj.boot.common.utils.QueryHelp;
import com.tckj.boot.common.utils.BeanUtils;

/**
* @author icodebug
* @date 2019-12-12 11:37:22
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class NewsService{

    @Autowired
    private NewsRepository repository;

    public Page<News> queryAll(NewsQueryCriteria criteria, Pageable pageable){
        return repository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
    }

    public List<News> queryAll(NewsQueryCriteria criteria){
        return repository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
    }

    public News findById(Long id) {
        Optional<News> news = repository.findById(id);
        return news.get();
    }

    @Transactional(rollbackFor = Exception.class)
    public News create(News resources) {
        if (resources.getId()==null){
            return repository.saveAndFlush(resources);
        }else{
            News target = findById(resources.getId());
            BeanUtils.copyNotNullProperties(resources,target);
            return repository.saveAndFlush(target);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        repository.deleteById(id);
    }
}